package pri.hillchen.std.concurrent.chapter5;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Semaphore;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 12:40 2018/2/8 0008.
 */
public class SemaphoreDemo {
    /*class Electioner{

    }
    interface ElectableRunner extends Runnable{
        Semaphore getSemaphore();
        default void elected() throws InterruptedException {
            getSemaphore().acquire();
        }
    }*/

    class BoundHashSet<T>{
        private final Set<T> set;
        private final Semaphore semaphore;

        public BoundHashSet(int bound) {
            this.set = new HashSet<T>(bound);
            this.semaphore = new Semaphore(bound);
        }

        public boolean add(T o) throws InterruptedException {
            semaphore.acquire();
            boolean wasAdded = false;
            try{
                wasAdded = set.add(o);
                return wasAdded;
            }finally {
                if(!wasAdded){
                    semaphore.release();
                }
            }
        }

        public boolean remove(T o){
            boolean wasRemove = set.remove(o);
            if(wasRemove){
                semaphore.release();
            }
            return wasRemove;

        }
    }
}
